﻿using LandPortMoblieWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LandPortMoblieWeb.Helper;


namespace LandPortMoblieWeb.Service
{
    public class UserService:PSIBaseService
    {
        /// <summary>
        /// 验证用户登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool IsLoginPass(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            var p = CreateDbParameters();
            p.AddWithValue("login", user.LoginName);
            p.AddWithValue("password", SimpleCrypt.Encode(user.Password));

            var sql = @"select count(*) from psi_user 
                        where (login_name = @login or tel=@login) and password = @password and enabled = 1";
         

            var count = QueryCount(sql, p);

            if (count != 1)
            {
                return false;
            }
            else
            {            
                return true;
            }
        }

        /// <summary>
        /// 得到用户实体
        /// </summary>
        /// <param name="LoginName"></param>
        /// <returns></returns>
        public User GetUserModel(string LoginName)
        {
            var sql = "select * from psi_user where login_name = @login or tel=@login" ;

            var result=new User();
            var p = CreateDbParameters();
            p.AddWithValue("login", LoginName);

            var u = QueryObject<User>(sql, p,
            reader =>
            {
              result= new User
                {
                    Id = reader.GetString(reader.GetOrdinal("user_id")),
                    Name = reader.GetString(reader.GetOrdinal("user_name")),
                    LoginName = reader.GetString(reader.GetOrdinal("login_name")),
                    Password = reader.GetString(reader.GetOrdinal("password")),
                };
              return result;
            });
            return result;

        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool ChangePassword(string userId, string password)
        {
            if (string.IsNullOrEmpty(password)) return false;

            var sql = "update psi_user set password = @password where user_id = @userId";
            var db = DBHelper.AdoTemplate;
            var p = db.CreateDbParameters();
            p.AddWithValue("userId", userId);
            p.AddWithValue("password", SimpleCrypt.Encode(password));
            var num=db.Execute(sql, p);

            if (num > 0)
                return true;
            else
                return false;
        }
    }
}